package com.etlmaster.executor.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 变量替换失败帮助类
 * 
 * @author Wugf
 * @date 2016-03-08
 */
public class GetErrorVars {
	public  String replaceString(String text,String key,String value,Map<String,Object> obj,List ls){
		String defaultString;
		if (obj.get(key) == null) {
			ls.remove(value);
			ls.add(value);
			defaultString = text.replace(value, "NULL");
		} else {
			defaultString = text.replace(value, obj.get(key)
					.toString());
		}
		return defaultString;
	} 
	public String replaceMap(String text,String key,String value,Map<String,String> hash,Map<String,Object> obj,List ls){
		String defaultString;
		String[] str = key.split("\\.");
		if (key.contains("[")) {
			obj = addNullVars(key, obj);
		}
		hash = (Map<String, String>) obj.get(str[0]);
		if (hash == null || hash.get(str[1]) == null) {
			ls.remove(value);
			ls.add(value);
			defaultString = text.replace(value, "NULL");

		} else {
			defaultString = text.replace(value,
					hash.get(str[1]));
		}
		return defaultString;
	}
	public static Map<String, Object> addNullVars(String name,
			Map<String, Object> obj) {
		String varName = name.substring(0, name.indexOf("["));

		Map<String, Object> rtn = new HashMap<String, Object>();
		Object instance = obj.get(varName);
		if (instance != null && instance instanceof List) {
			int i = 0;
			for (Object inner : (List) instance) {
				rtn.put(varName + "[" + i + "]", inner);
				i++;
			}
		} else {
			String newVarName = name.substring(0, name.indexOf("."));
			String key = name.substring(name.indexOf(".") + 1);
			Map<String, String> map = new HashMap<String, String>();
			map.put(key, "null");
			rtn.put(newVarName, map);
		}
		rtn.putAll(obj);
		return rtn;
	}
}
